import React from "react";
import PropTypes from "prop-types";
// 这里有坑 ContentState是draft-js里面的  因为其他包里也有相同名字的ContentState是draft
import { EditorState, convertToRaw, ContentState } from "draft-js";
import { Editor } from "react-draft-wysiwyg";
import draftToHtml from "draftjs-to-html";
import htmlToDraft from "html-to-draftjs";
import "react-draft-wysiwyg/dist/react-draft-wysiwyg.css";

interface Iprops {
  detail: string;
}

class RichTextEditor extends React.Component<any, any> {
  // props类型约束
  static propTypes = {
    detail: PropTypes.string,
  };
  state = {
    // 创建一个空的编辑对象
    editorState: EditorState.createEmpty(),
  };

  constructor(props: Iprops) {
    super(props);
    // 从props中拿到父组件穿过来的 detail 转换过后显示在富文本输入框内
    const html = props.detail;
    if (html && html.length > 0) {
      // 把拿到的内容进行转换 并且显示到输入框内
      const contentBlock = htmlToDraft(html);
      if (contentBlock) {
        const contentState = ContentState.createFromBlockArray(
          contentBlock.contentBlocks
        );
        const editorState = EditorState.createWithContent(contentState);
        this.state = {
          editorState,
        };
      }
      // 如果没有给到富文本detail的描述信息  就置空
    } else {
      this.state = { editorState: EditorState.createEmpty() };
    }
  }

  onEditorStateChange: any = (editorState: any) => {
    this.setState({
      editorState,
    });

    // draftToHtml(convertToRaw(editorState.getCurrentContent()))将输入的富文本转换为html的标签内容
    // console.log(draftToHtml(convertToRaw(editorState.getCurrentContent())));
  };

  // 单独抽离为一个方法 将输入的富文本转换为html的标签内容
  // draftToHtml(convertToRaw(editorState.getCurrentContent()))将输入的富文本转换为html的标签内容
  getInputDraft = () => {
    return draftToHtml(
      convertToRaw(this.state.editorState.getCurrentContent())
    );
  };
  render() {
    const { editorState } = this.state;
    return (
      <div>
        <Editor
          editorState={editorState}
          wrapperClassName="demo-wrapper"
          editorClassName="demo-editor"
          editorStyle={{
            border: "1px solid #d9d9d9",
            minHeight: "200px",
            paddingLeft: "15px",
          }}
          onEditorStateChange={this.onEditorStateChange}
        />
        {/* <textarea
          disabled
          style={{
            border: "1px solid #d9d9d9",
            minHeight: "200px",
            paddingLeft: "15px",
          }}
          value={draftToHtml(convertToRaw(editorState.getCurrentContent()))}
        /> */}
      </div>
    );
  }
}

export default RichTextEditor;

// 视频P83
